<?php

namespace app\model;

use app\api\service\WechatSubscribeService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\facade\Queue;
use think\Model;

class Videos extends Model
{
    // 设置当前模型对应的数据表
    protected $name = 'videos';
    // 设置当前模型主键
    protected $pk = 'id';

    //上架状态
    const IS_SHELVES_NO = 0;//未上架
    const IS_SHELVES_YES = 1;//已上架
    const IS_SHELVES_ARR = [
        self::IS_SHELVES_NO => '未上架',
        self::IS_SHELVES_YES => '已上架',
    ];

    const VIDEO_TYPES = [
        1 => '最新',
        2 => '热门',
        3 => '免费'
    ];

    // protected $append =[
    //     "name",
    // ];
    // public function getNameAttr($value,$data){
    //     $value=isset($data['original_id'])? $data['original_id']:'';
    //     if(empty($value)){
    //         return isset($data['name'])? $data['name']:'';
    //     }
    //     $videoname=Db::name('videos')->where('id',$data['original_id'])->find();
    //     return empty($videoname)?'':$videoname['name'];
    // }
  
    public function rechargeLimitTemplateVideo()
    {
        return $this->hasOne(RechargeLimitTemplateVideo::class, 'video_id', 'id');
    }

    /**
     * 根据ids获取数据
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param array ids
     * @param string fields
     * @param string order
     * @return array
     */
    public function getDataByIds(array $ids, string $fields = 'id', string $order = 'sort desc')
    {
        $data = $this::where(['id' => $ids])->field($fields)->order($order)->select();
        return $data ? $data->toArray() : [];
    }

    /**
     * 获取推荐数据
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param string fields
     * @param string order
     * @return array
    */
    public function getRecommendedData(array $where, string $fields = 'id', int $page = 1, int $limit = 1, string $order = 'sort desc')
    {
        $offset = ($page - 1) * $limit;

        $total = $this::where($where)->count();
        if ($total == 0) {
            return ['total_page' => 0, 'total' => 0, 'data' => []];
        }

        $totalPage = ceil($total / $limit);
        $data = $this::field($fields)->where($where)->order($order)->limit($offset, $limit)->select();
        $data = $data ? $data->toArray() : [];

        return ['total_page' => $totalPage, 'total' => $total, 'data' => $data];
    }

    /**
     * 获取分类id获取数据
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param int videoTypeId
     * @param int page
     * @param int limit
     * @param string fields
     * @param string order
     * @return array
    */
    public function getDataByVideoTypeId($videoTypeId, $page = 1, $limit = 10, $fields = 'id', $order = 'sort desc')
    {
        $offset = ($page - 1) * $limit;

        $total = $this::where(['video_type_id' => $videoTypeId, 'is_delete' => 0, 'is_shelves' => 1])->count();

        $totalPage = ceil($total / $limit);

        $data = $this::where(['video_type_id' => $videoTypeId, 'is_delete' => 0, 'is_shelves' => 1])->field($fields)->order($order)->limit($offset, $limit)->select();
        $data = $data ? $data->toArray() : [];

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    /**
     * 根据分类ID获取电视剧（新版）by huangxiaoshan add 2023-07-24
     * @param array $where
     * @param int $page
     * @param int $limit
     * @param string $fields
     * @param string $order
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDataByVideoTypeIdNew($where=[], $page = 1, $limit = 10, $fields = 'id', $order = 'sort desc')
    {
        $offset = ($page - 1) * $limit;

        $total = $this::where($where)->count();

        $totalPage = ceil($total / $limit);

        $data = $this::where($where)->field($fields)->order($order)->limit($offset, $limit)->select();
        $data = $data ? $data->toArray() : [];

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    /**
     * 根据id获取数据
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param int id
     * @param string fields
     * @return array
    */
    public function getInfoById($id, $fields = 'id, name')
    {
        $data = $this::where(['id' => $id])->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    public function getCacheInfoById($id, $fields = 'id, name')
    {
        $data = $this::where(['id' => $id])->field($fields)->cache(true,60)->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 根据id获取数据
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param int id
     * @param string fields
     * @return array
    */
    public function getWithRechargeVideoInfoById(int $id, $fields = 'id, name')
    {
        $data = $this::with(['rechargeLimitTemplateVideo' => function ($query) {
            $query->withField(['recharge_limit_template_id', 'video_id']);
        }])->where(['id' => $id])->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 获取数据
     * 
     * @dateTime 2022/09/03
     * @author zhixiang0215@126.com
     * @param array where
     * @param int page
     * @param int limit
     * @param string fields
     * @param string order
     * @return array
     */
    public function getPagingDataByWhere(array $where, int $page = 1, int $limit = 10, string $fields = 'id', string $order = 'give_count desc')
    {
        $offset = ($page - 1) * $limit;
        if ($offset < 0) $offset = 0;

        $total = $this::where($where)->count();

        if ($total == 0) return ['total' => 0, 'total_page' => 0, 'data' => []];
        $totalPage = ceil($total / $limit);

        $data = $this::where($where)->field($fields)->order($order)->limit($offset, $limit)->select()->toArray();

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

        /**
     * 获取数据
     * 
     * @dateTime 2022/09/03
     * @author zhixiang0215@126.com
     * @param array where
     * @param int page
     * @param int limit
     * @param string fields
     * @param string order
     * @return array
     */
    public function getWithRechargeVideoPagingDataByWhere(array $where, int $page = 1, int $limit = 10, string $fields = 'id', string $order = 'give_count desc')
    {
        $offset = ($page - 1) * $limit;
        if ($offset < 0) $offset = 0;

        $total = $this::where($where)->count();

        if ($total == 0) return ['total' => 0, 'total_page' => 0, 'data' => []];
        $totalPage = ceil($total / $limit);

        $data = $this::with(['rechargeLimitTemplateVideo' => function ($query) {
            $query->with(['rechargeLimitTemplate' => function($query){
                $query->withField(['id', 'recharge_name']);
            }])->withField(['recharge_limit_template_id', 'video_id']);
        }])->where($where)->field($fields)->order($order)->limit($offset, $limit)->select()->toArray();

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    /**
     * 获取数据
     * 
     * @dateTime 2022/09/03
     * @author zhixiang0215@126.com
     * @param array where
     * @param string fields
     * @param string order
     * @param int limit
     * @return array
     */
    public function getDataByWhere(array $where, string $fields = '', string $order = 'sort desc', int $limit = 0)
    {
        $model = $this::where($where)->field($fields)->order($order);

        if ($limit) {
            $model->limit($limit);
        }

        $data = $model->select();
        return $data ? $data->toArray() : [];
    }

    /**
     * 通过模糊查询name获取数据
     * 
     * @dateTime 2022/09/05
     * @author zhixiang0215@126.com
     * @param string name
     * @param string fields
     * @return array
     */
    public function getDataByLikeName(string $name, string $fields = '')
    {
        $data = $this::whereLike('name', '%'.$name.'%')->where(['is_delete' => 0, 'is_shelves' => 1])->field($fields)->select();
        return $data ? $data->toArray() : [];
    }

    /**
     * 新版搜索支持按平台进行数据过滤.
     * @param string $name
     * @param string $fields
     * @param array $where
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDataByLikeNameNew(string $name, string $fields = '',array $where=[])
    {
        $data = $this::whereLike('name', '%'.$name.'%')->where($where)->field($fields)->select();
        return $data ? $data->toArray() : [];
    }

    // 获取总点赞数
    public function getGiveCount($where)
    {
        $data = $this::where($where)->field('give_count')->select();
        return $data ? $data->toArray() : [];
    }

    /**
     * 添加/编辑
     * 
     * @dateTime 2022/09/19
     * @author zhixiang0215@126.com
     * @param array $params
     * @return int
     */
    public function edit(array $params)
    {
        if (empty($params['id'])) {
            $data = $this::create($params);
            return $data->id;
        }
        $this::update($params);
        return $params['id'];
    }

    /**
     * 获取一条数据
     * 
     * @dateTime 2023/02/21
     * @author zhixiang0215@126.com
     * @param array where
     * @param string fields
     * @param string order
     * @return array
     */
    public function getInfoByWhere(array $where, string $fields = 'id', $order = '')
    {
        $model = $this::where($where)->field($fields);

        if ($order) {
            $model->order($order);
        }

        $data = $model->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 更新后操作
     * @param Videos $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function onAfterUpdate(Videos $model) {
        try {
            $video = self::find($model->id)->toArray();
            //上架后订阅消息推送
            if (
                $model->getOrigin("is_shelves") == self::IS_SHELVES_NO
                && $model->is_shelves == self::IS_SHELVES_YES
            ){
                if ($video){
                    $videoDetail = VideoDetails::where('video_id',$model->id)->order('sort','ASC')->find();
                    $videoDetailId = $videoDetail->id ?? 0;
                    $data = [
                        'type'  => WechatSubscribeService::TYPE_NEW_VIDEO_ONLINE,//类型
                        'thing1' => $video['name'],//视频名称
                        'thing2' => $video['synopsis'],//视频描述
                        'time3' => date('Y-m-d H:i:s'),//上线时间
                        'page' => "/pages/index/index?video_id={$model->id}&video_detail_id={$videoDetailId}&source=link",//跳转地址
                    ];
                    Queue::push('app\job\WechatSubscribeSendJob', $data, 'wechat-subscribe-send');
                }
            }
        }catch (\Throwable $e){
            flog([
                'message' => $e->getMessage(),
                'data' => $model->toArray(),
            ],'video_update','error');
        }
    }

    /**
     * 新增后操作
     * @param Videos $model
     * @return void
     */
    public static function onAfterInsert(Videos $model) {
        try {
            //上架后订阅消息推送
            if ($model->is_shelves == self::IS_SHELVES_YES){
                $videoDetail = VideoDetails::where('video_id',$model->id)->order('sort','ASC')->find();
                $videoDetailId = $videoDetail->id ?? 0;
                $data = [
                    'type'  => WechatSubscribeService::TYPE_NEW_VIDEO_ONLINE,//类型
                    'thing1' => $model->toArray()['name'] ?? '',//视频名称
                    'thing2' => $model->synopsis,//视频描述
                    'time3' => date('Y-m-d H:i:s'),//上线时间
                    'page' => "/pages/index/index?video_id={$model->id}&video_detail_id={$videoDetailId}&source=link",//跳转地址
                ];
                Queue::push('app\job\WechatSubscribeSendJob', $data, 'wechat-subscribe-send');
            }
        }catch (\Throwable $e){
            flog([
                'message' => $e->getMessage(),
                'data' => $model->toArray(),
            ],'video_update','error');
        }
    }
}